package com.zl.view;

import java.awt.EventQueue;

import javax.swing.JInternalFrame;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import com.zl.dao.BookBorrowDao;
import com.zl.dao.BookDao;
import com.zl.model.Book;
import com.zl.model.BookBorrow;
import com.zl.model.User;
import com.zl.util.ZLString;
import com.zl.util.ZLUtil;

import javax.swing.JButton;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.Font;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;

public class BookReturnFrame extends JInternalFrame {
	private JTable table;
	private int selectedRow;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					BookReturnFrame frame = new BookReturnFrame();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public BookReturnFrame() {
		setClosable(true);
		setIconifiable(true);
		setTitle("图书归还");
		setBounds(100, 100, 522, 357);
		
		JScrollPane scrollPane = new JScrollPane();
		
		JButton btnNewButton = new JButton("归还图书");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				returnBookAction(arg0);
			}
		});
		btnNewButton.setIcon(new ImageIcon(BookReturnFrame.class.getResource("/images/me.png")));
		
		JLabel label = new JLabel("当前您所借阅的图书如下，请按时归还");
		label.setFont(new Font("宋体", Font.BOLD, 17));
		
		JButton btnNewButton_1 = new JButton("重置");
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				refreshReturnBookAction(arg0);
			}
		});
		btnNewButton_1.setIcon(new ImageIcon(BookReturnFrame.class.getResource("/images/reset.png")));
		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout.setHorizontalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(45)
							.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 414, GroupLayout.PREFERRED_SIZE))
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(118)
							.addComponent(btnNewButton)
							.addGap(83)
							.addComponent(btnNewButton_1, GroupLayout.PREFERRED_SIZE, 89, GroupLayout.PREFERRED_SIZE))
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(86)
							.addComponent(label)))
					.addContainerGap(47, Short.MAX_VALUE))
		);
		groupLayout.setVerticalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addGap(46)
					.addComponent(label)
					.addGap(18)
					.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 167, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(btnNewButton)
						.addComponent(btnNewButton_1))
					.addGap(27))
		);
		
		table = new JTable();
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent arg0) {
				bookTableMousePressed(arg0);
			}
		});
		table.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"\u7F16\u53F7", "\u4E66\u540D", "\u501F\u9605\u65E5\u671F", "\u5F53\u524D\u662F\u5426\u5F52\u8FD8"
			}
		) {
			boolean[] columnEditables = new boolean[] {
				false, false, false, false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		table.getColumnModel().getColumn(3).setPreferredWidth(124);
		scrollPane.setViewportView(table);
		getContentPane().setLayout(groupLayout);

		User currentLoginUser = LoginFrame.loginSuccessUser;
		BookBorrow bookBorrow = new BookBorrow();
		bookBorrow.setUserId(currentLoginUser.getId());
		this.fillTable(bookBorrow);
	}
	
	/**
	 * 	刷新页面
	 * @param arg0
	 */
	private void refreshReturnBookAction(ActionEvent arg0) {
		// TODO Auto-generated method stub
		User currentLoginUser = LoginFrame.loginSuccessUser;
		BookBorrow bookBorrow1 = new BookBorrow();
		bookBorrow1.setUserId(currentLoginUser.getId());
		this.fillTable(bookBorrow1);
	}

	/**
	 * 图书归还
	 * @param arg0
	 */
	private void returnBookAction(ActionEvent arg0) {
		// TODO Auto-generated method stub
		int id = Integer.parseInt((String)table.getValueAt(selectedRow, 0));
		
		if (id == 0) {
			JOptionPane.showMessageDialog(null, "请选择需要归还的图书");
		}
		
		String returnTime = (long)System.currentTimeMillis() + "";//获取当前系统时间戳
		
		BookBorrow bookBorrow = new BookBorrow();
		bookBorrow.setId(id);
		bookBorrow.setReturnTime(returnTime);
		bookBorrow.setIsReturn(true);
		bookBorrow.setIsAppointMent(0);
		Connection connection = null;
		
		try {
			
			connection = ZLUtil.getConnect();
			int success = BookBorrowDao.update(connection, bookBorrow);
			if (success == 1) {
				
				JOptionPane.showMessageDialog(null, "归还图书成功");
				
				User currentLoginUser = LoginFrame.loginSuccessUser;
				BookBorrow bookBorrow1 = new BookBorrow();
				bookBorrow1.setUserId(currentLoginUser.getId());
				this.fillTable(bookBorrow1);
			}else {

				JOptionPane.showMessageDialog(null, "归还图书失败");
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			
			try {
				ZLUtil.colseConnect(connection);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 表格行点击事件处理
	 * @param met
	 */
	private void bookTableMousePressed(MouseEvent met) {
		
		selectedRow = this.table.getSelectedRow();
	}
	
	/**
	 * 初始化表格数据
	 * @param book
	 */
	private void fillTable(BookBorrow bookBorrow){
		DefaultTableModel dtm=(DefaultTableModel) table.getModel();
		dtm.setRowCount(0); // 设置成0行

		Connection connection = null;
		try{
			connection = ZLUtil.getConnect();
			ResultSet set = BookBorrowDao.select(connection, bookBorrow);
			while(set.next()){

				if (!set.getBoolean("isReturn")) {//未归还的图书
					Vector v=new Vector();
					v.add(set.getString("id"));
					v.add(set.getString("bookName"));
					v.add(ZLString.timeStamp2Date(set.getString("borrowTime")));
					v.add("否");
					dtm.addRow(v);
				}

			}
		}catch(Exception e){
			
			e.printStackTrace();
		}finally{
			try {
				ZLUtil.colseConnect(connection);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
